<template>
    <div class="login">
        <el-form 
            :model="form" 
            ref="form" 
            label-width="100px"
            label-position="top"
            :rules="rules"
        >
          <el-form-item 
            label="账号"
            prop="phone"
          >
            <el-input v-model="form.phone"></el-input>
          </el-form-item>
          <el-form-item 
            label="密码"
            prop="password"
          >
            <el-input 
                type="password"
                v-model="form.password"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button 
                type="primary"
                @click="onSubmit"
                :loading="isLoginLoading"
            >登录</el-button>
          </el-form-item>
        </el-form>
    </div>
</template>

<script>
// 引入封装的接口功能组件
import { login } from '@/services/user.js'
export default {
    name: 'LoginIndex',
    data () {
        return {
            // 表单
            form: {
                phone: '18201288771',
                password: '111111'
            },
            // 表单校验规则
            rules: {
                phone: [
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ]
            },
            // 用于保存加载状态(button按钮)
            isLoginLoading: false
        }
    },
    methods: {
        async onSubmit () {
            try {
                await this.$refs.form.validate()
                // 发送请求
                this.isLoginLoading = true
                const { data } = await login(this.form)
                this.isLoginLoading = false
                // 响应数据处理
                if (data.state === 1) {
                    this.$message.success('登录成功')
                    // 将用户信息存储到vuex中
                    this.$store.commit('setUser', data.content)
                    this.$router.push(this.$route.query.redirect || '/')
                } else {
                    this.$message.error('登录失败')
                }
            } catch (err) {
                console.log('没有通过校验')
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.login {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    .el-form {
        background-color: #fff;
        padding: 20px;
        width: 300px;
        border-radius: 10px;
        .el-button {
            width: 100%;
        }
    }
}
</style>